package com.system.connect.springboot_flowers.controller;


import com.system.connect.springboot_flowers.dto.AddressDTO;
import com.system.connect.springboot_flowers.entity.UserAddress;
import com.system.connect.springboot_flowers.service.IUserAddressService;
import com.system.connect.springboot_flowers.utils.R;
import com.system.connect.springboot_flowers.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户收货地址表 前端控制器
 * </p>
 *
 * @author yang
 * @since 2025-03-22
 */
@RestController
@RequestMapping("/api/address")
public class UserAddressController {
    @Autowired
    private IUserAddressService addressService;

    /**
     * 获取用户地址列表
     */
    @GetMapping("/list")
    public R getAddressList() {
        // 获取当前登录用户的ID
        Integer userId = Integer.valueOf(TokenUtils.getUser());
        List<UserAddress> addresses = addressService.getAddressList(Long.valueOf(userId));
        return R.success(addresses);
    }

    /**
     * 新增地址
     */
    @PostMapping("/add")
    public R addAddress(@RequestBody AddressDTO addressDTO) {
        Integer userId = Integer.valueOf(TokenUtils.getUser());
        addressService.addAddress(Long.valueOf(userId), addressDTO);
        return R.success("新增地址成功");
    }

    /**
     * 更新地址
     */
    @PostMapping("/update")
    public R updateAddress(@RequestBody AddressDTO addressDTO) {
        Integer userId = Integer.valueOf(TokenUtils.getUser());
        addressService.updateAddress(Long.valueOf(userId), addressDTO);
        return R.success("地址更新成功");
    }

    /**
     * 删除地址
     */
    @PostMapping("/delete")
    public R deleteAddress(@RequestBody Map<String, Long> params) {
        Integer userId = Integer.valueOf(TokenUtils.getUser());
        addressService.deleteAddress(Long.valueOf(userId), params.get("id"));
        return R.success("成功删除地址");
    }

    /**
     * 设置默认地址
     */
    @PostMapping("/setDefault")
    public R setDefaultAddress(@RequestBody Map<String, Long> params) {
        Integer userId = Integer.valueOf(TokenUtils.getUser());
        addressService.setDefaultAddress(Long.valueOf(userId), params.get("id"));
        return R.success("设置默认地址成功");
    }
}

